package com.es.utils;

import com.es.entity.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.util.LinkedList;
import java.util.List;

@Component
public class HtmlParseUtil {

    public List<Content> parseJD(String keyword) throws Exception {
        String url = "https://search.jd.com/Search?keyword=" + keyword;
        Document parse = Jsoup.parse(new URL(url), 30000);
        Element element = parse.getElementById("J_goodsList");
        Elements li = element.getElementsByTag("li");
        List<Content> contents = new LinkedList<>();
        for (Element elements : li) {
            String img = elements.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = elements.getElementsByClass("p-price").eq(0).text();
            String name = elements.getElementsByClass("p-name").eq(0).text();
            String publishingHouse = elements.getElementsByClass("p-shopnum").eq(0).text();
            contents.add(Content
                    .builder()
                    .imageUrl(img)
                    .name(name)
                    .price(price)
                    .publishingHouse(publishingHouse)
                    .build());
        }
        return contents;
    }
}
